package com.springboot.jwt.controller;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.springboot.jwt.anno.ResponseNotIntercept;
import com.springboot.jwt.entity.User;
import com.springboot.jwt.exception.BizException;
import com.springboot.jwt.service.UserService;
import com.springboot.jwt.utils.JwtUtil;
import com.tutorials.common.utils.R;
import com.tutorials.common.utils.ResponseVO;
import io.micrometer.common.util.StringUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
public class UserContorller {

    private UserService userService;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService=userService;
    }

    @GetMapping("/user/login")
    public R login()
    {
        log.info("用户名[{}]", "zhongxc");
        log.info("密码[{}]", "123456");

        User user = userService.login("zhongxc", "123456");
        HashMap<String, String> payload = new HashMap<>();
        payload.put("id", user.getId().toString());
        payload.put("name", user.getName());

        // 生成jwt令牌
        String token = JwtUtil.getToken(payload);
        Map<String, Object> jwtMap = new HashMap<>();
        jwtMap.put("token", token);

        return R.ok().put("data", jwtMap);
    }

    @PostMapping("/user/test")
    public Map<String, Object> test(HttpServletRequest request)
    {
        // Integer.parseInt("ABC123");
        String token = request.getHeader("Authorization");
        if (token==null){
            throw new BizException("-1", "token不能为空");
        }
        if (token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        DecodedJWT verify = JwtUtil.verify(token);

        HashMap<String, Object> map = new HashMap<>();
        map.put("id", verify.getClaim("id").asString());
        map.put("name", verify.getClaim("name").asString());

        // return ResponseVO.success(map);
        return map;
    }

    @PostMapping("/user/update/{id}")
    @ResponseNotIntercept
    public void update(@PathVariable("id") Long id) {
        if (id == null) {
            throw new BizException("400", "id不能为空");
        }

        log.info("用户更新成功:{}", id);
    }

}
